package com.baizhi.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisUtils {
    private static JedisPool pool;
    static{
        //读取redis.properties文件
        InputStream in = JedisUtils.class.getResourceAsStream("/redis.properties");
        Properties env = new Properties();
        try {
            env.load(in);
            in.close();
        }catch(IOException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        JedisPoolConfig config = new JedisPoolConfig();
        String maxIdle = env.getProperty("redis.maxIdle");
        if (maxIdle != null) {
            config.setMaxIdle(Integer.parseInt(maxIdle));
        }
        String minIdle = env.getProperty("redis.minIdle");
        if(minIdle != null){
            config.setMinIdle(Integer.parseInt(minIdle));
        }
        String maxTotal = env.getProperty("redis.maxTotal");
        if(maxTotal != null){
            config.setMaxTotal(Integer.parseInt(maxTotal));
        }
        String maxWaitMillis = env.getProperty("redis.maxWaitMillis");
        if (maxWaitMillis != null) {
            config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
        }
        String testOnBorrow = env.getProperty("redis.testOnBorrow");
        if(testOnBorrow != null){
            config.setTestOnBorrow(Boolean.parseBoolean(testOnBorrow));
        }

        String hostName = env.getProperty("redis.hostName");
        String port = env.getProperty("redis.port");

        pool = new JedisPool(config, hostName, Integer.parseInt(port == null ? "6379" : port));
    }

    public static Jedis getJedis(){
        return pool.getResource();
    }

    public static void close(Jedis jedis){
        if(jedis != null){
            jedis.close();
        }
    }
}